#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;

#[allow(unused)]
pub mod console_option {
    pub const CREATE_NEW_CONSOLE: u32 = 0x00000010;
    pub const DETACHED_PROCESS: u32 = 0x00000008;
    pub const CREATE_NO_WINDOW: u32 = 0x08000000;
}

pub fn run_fd(env_path: &str, cmd: &str) -> Result<String, String> {
    let mut err_msg = String::new();
    let cur_path = std::env::current_exe().unwrap();

    #[cfg(target_os = "windows")]
    let name = "fd.exe";

    #[cfg(not(target_os = "windows"))]
    let name = "fd";

    let fd = cur_path.parent().unwrap().join(name);
    println!("{}", fd.to_str().unwrap());

    let output;
    let command_str;

    // make sure version is right on window
    #[cfg(target_os = "windows")]
    {
        command_str = format!("{} {}", fd.to_str().unwrap(), cmd);
        output = std::process::Command::new("cmd")
            .current_dir(env_path)
            .arg("/C")
            .arg(&command_str)
            .creation_flags(console_option::CREATE_NO_WINDOW)
            .output()
            .expect("command failed to start");
    }

    // make sure version is right on not window
    #[cfg(not(target_os = "windows"))]
    {
        let cur_path = cur_path.parent().unwrap().to_str().unwrap();
        command_str = format!("{} {}", fd.to_str().unwrap(), cmd);
        output = std::process::Command::new("sh")
            .current_dir(cur_path)
            .arg("-c")
            .arg(&command_str)
            .output()
            .expect("command failed to start");
    }

    if output.status.success() {
        let s = String::from_utf8(output.stdout).expect("fd error");
        return Ok(s);
    } else {
        err_msg.push_str(&format!("Error : Command run error - {}", command_str));
    }

    return Err(err_msg);
}
